﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ShunFengApi.Common
{
    public static class HttpHelper
    {
        /// <summary>
        /// 发送POST请求（application/json）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jsonParam"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static T PostJson<T>(string url, string jsonParam, string encode = "utf-8") where T : new()
        {
            T result = new T();
            string strURL = url;
            System.Net.HttpWebRequest request;
            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            request.Method = "POST";
            request.ContentType = "application/json;charset=" + encode.ToUpper();
            string paraUrlCoded = jsonParam;
            byte[] payload;
            payload = System.Text.Encoding.GetEncoding(encode.ToUpper()).GetBytes(paraUrlCoded);
            request.ContentLength = payload.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(payload, 0, payload.Length);
            writer.Close();
            try
            {
                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream s;
                s = response.GetResponseStream();
                string StrDate = "";
                string strValue = "";
                StreamReader Reader = new StreamReader(s, Encoding.GetEncoding(encode.ToUpper()));
                while ((StrDate = Reader.ReadLine()) != null)
                {
                    strValue += StrDate + "\r\n";
                }
                if (!string.IsNullOrEmpty(strValue))
                {
                    result = JsonConvert.DeserializeObject<T>(strValue);
                }
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog("发送POST请求（application/json）:URL:"+url+"；\r\n 异常信息：" + ex.ToString(), LogType.error);
            }
            return result;
        }
    }
}
